package cn.rengy.web.framework.shiro.filter.authc;


import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.springframework.http.HttpHeaders;

import cn.rengy.tool.web._WebUtils;
import cn.rengy.web.framework.shiro.token.JwtToken;
import lombok.extern.slf4j.Slf4j;

/**
 * JWT 登录认证
 * @author rengy
 *
 */
@Slf4j
public class StatelessAuthenticationFilter extends IAuthenticationFilter {
	
	public StatelessAuthenticationFilter(){
    	setName("jwtLogin");
    }
	private final String tokenHeader=HttpHeaders.AUTHORIZATION;
	public static final String tokenHead="Bearer ";
	
	@Override
	protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object mappedValue) {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		String authHeader=request.getHeader(tokenHeader);
		if (authHeader != null && authHeader.startsWith(tokenHead)) {
			String authToken = authHeader.substring(tokenHead.length());
			if(StringUtils.isNotEmpty(authToken)) {
				JwtToken token= new JwtToken(authToken,_WebUtils.getUserAgent(request),_WebUtils.getClientIp(request));
	            try {
	            	getSubject(request, response).login(token);
	            	return true;
	            }catch(AuthenticationException e) {
	            	return false;
	            }
			}else {
				return false;
			}
		}else {
			log.warn("没有token或token格式不正确");
			return false;
		}
		
    	/*LOGGER.debug("<header");
    	for (Enumeration<String> eh = request.getHeaderNames(); eh.hasMoreElements();){
			String key = eh.nextElement();
			String value = request.getHeader(key);
			LOGGER.debug("{}={}",key,value);
		}
    	LOGGER.debug("header>");*/
		//
		
	}
	
	
}
